# Create your views here.
import os
import uuid
import threading
from PIL import Image
from django.core.paginator import Paginator
from django.db import transaction
from django.db.models import Q
from rest_framework.decorators import api_view

from files.db_sql import *
from files.method import *
from method.email import *
from method.method import cccc

now = datetime.datetime.now()


@api_view(http_method_names=["GET", "POST"])
def cutters(request):
    """
    刀具类别接口：\n
    方法：GET ， POST
    1.POST 参数 cutter_type ： 刀具类别

    :param request:
    :return:

    """

    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        cutter_id = request.GET.get("id", None)
        if cutter_id:
            result = TbCutterType.objects.filter(id=cutter_id).exclude(is_customer=1)
        else:
            result = TbCutterType.objects.exclude(is_customer=1)
        if result:
            for i in result:
                content["payload"].append({
                    "id": i.id, "cutter_type": i.cutter_type,
                    "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S")
                })
    elif request.method == "POST":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            cur = request.data["cutter_type"]
            is_cus = request.data["is_customer"] if "is_customer" in request.data.keys() else 0
            last_name = TbCutterType.objects.all()

            for i in last_name:
                if cur == i.cutter_type:
                    content["errmsg"] = "提交名字已經存在，請重新命名！"
                    content["status"] = 0
                    return Response(content)

            repetition = TbCutterType.objects.filter(cutter_type=cur)
            if repetition:
                content["errmsg"] = "the cutter_type exist"
                content["status"] = 0
            else:
                TbCutterType.objects.create(cutter_type=cur, create_time=now)
                content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def cutter(request, pk):
    """
    刀具类别实例接口：\n
    方法：GET ，PUT, DELETE \n
    1.PUT 参数 cutter_type ： 刀具类别

    :param request:
    :return:
    """
    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        result = TbCutterType.objects.filter(id=pk)
        if result:
            for i in result:
                content["payload"].append({
                    "id": i.id, "cutter_type": i.cutter_type,
                    "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S")
                })

    elif request.method == "PUT":
        try:
            content = {"payload": [], "status": 1, "errmsg": None}
            change = request.data["cutter_type"]
            last_name = TbCutterType.objects.exclude(id=pk)
            for i in last_name:
                if change == i.cutter_type:
                    content["errmsg"] = "提交名字已經存在，請重新命名！"
                    content["status"] = 0
                    return Response(content)
            TbCutterType.objects.filter(id=pk).update(cutter_type=change)
            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    elif request.method == "DELETE":
        content = {"payload": [], "status": 1, "errmsg": None}
        TbProdectStarge.objects.filter(type_id=pk).update(type_id=None)
        TbCutterType.objects.filter(id=pk).delete()
        content["payload"] = "Success"
    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def stages(request):
    """
    產品階段接口 \n
    需要POST參數: "stage":階段名，"cutter_id":刀具類名id \n
    """
    if request.method == "POST":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            content["payload"] = []
            s_data = request.data
            is_cur = s_data["is_customer"] if "is_customer" in s_data.keys() else 0
            last_name = TbProdectStarge.objects.all()
            for i in last_name:
                if s_data["stage"] == i.product_stage and i.type_id == int(s_data["cutter_id"]):
                    content["errmsg"] = "提交名字已經存在，請重新命名！"
                    content["status"] = 0
                    return Response(content)
            TbProdectStarge.objects.create(product_stage=s_data["stage"], is_customer=is_cur,
                                           type_id=s_data["cutter_id"], create_time=now)
            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
        return Response(content)

    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        cur_id = request.GET.get("cutter_id")
        if cur_id:
            result = TbProdectStarge.objects.filter(type__id=cur_id)
        else:
            result = TbProdectStarge.objects.exclude(is_customer=1)

        if result:
            for i in result:
                content["payload"].append({
                    "id": i.id, "stage": i.product_stage,
                    "cutter_type": i.type.cutter_type if i.type else None,
                    "cutter_id": i.type.id if i.type else None,
                    "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S")
                })
        return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def stage(request, pk):
    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        result = TbProdectStarge.objects.filter(id=pk)

        if result:
            for i in result:
                content["payload"].append({
                    "id": i.id, "stage": i.product_stage,
                    "cutter_type": i.type.cutter_type,
                    "cutter_id": i.type.id,
                    "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S")
                })
        return Response(content)

    elif request.method == "PUT":

        content = {"payload": [], "status": 1, "errmsg": None}
        s_data = request.data
        try:
            last_name = TbProdectStarge.objects.exclude(id=pk)
            for i in last_name:
                change = TbCutterType.objects.filter(id=s_data["cutter_id"]).values_list("cutter_type", flat=1)[0]
                if s_data["stage"] == i.product_stage and (
                                s_data["cutter_id"] == i.type_id or change == i.type.cutter_type):
                    content["errmsg"] = "提交名字已經存在，請重新命名！"
                    content["status"] = 0
                    return Response(content)
            TbProdectStarge.objects.filter(id=pk).update(product_stage=s_data["stage"],
                                                         type_id=s_data["cutter_id"])
            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
        return Response(content)

    elif request.method == "DELETE":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            TbDrawing.objects.filter(cutter_id=pk).update(cutter_id=None)
            TbProdectStarge.objects.filter(id=pk).delete()
            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
        return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def drawing_types(request):
    """
    圖紙類別接口：\n
    1 .POST 參數 "drawing_type":圖紙類名, "stage_id"：工程階段,"cutter_id":刀具类型 \n
    2.GET 参数 search 为搜索关键字，page 为页数（默认20一页） 不传不分页 \n

    """
    if request.method == "POST":
        try:
            content = {"payload": [], "status": 1, "errmsg": None}
            data = request.data
            user = request.user.username + "(" + request.user.last_name + ")"
            seal_id_list = eval(data["seal_id_list"])
            if not seal_id_list:
                content["errmsg"] = "請選擇電子印章！"
                content["status"] = 0
                return Response(content)
            with transaction.atomic():
                last_name = TbDrawing.objects.exclude(is_delete=1)
                for i in last_name:
                    if data["drawing_type"] == i.drawing_type and i.cutter_id == data["stage_id"]:
                        content["errmsg"] = "提交名字已經存在，請重新命名！"
                        content["status"] = 0
                        return Response(content)
                drawing_obj = TbDrawing.objects.create(drawing_type=data["drawing_type"],
                                                       cutter_id=data["stage_id"],
                                                       create_time=now, creator=user)
                # print(drawing_obj.id, old_seal)
                seal_list = [TbDrawingSeal(seal_id=int(i),
                                           drawing_id=drawing_obj.id,
                                           creator=user,
                                           create_time=now) for i in eval(data["seal_id_list"])]

                TbDrawingSeal.objects.bulk_create(seal_list)

            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    elif request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        search = request.GET.get("search", None)
        page_num = request.GET.get("page", None)
        stage = request.GET.get("stage", None)
        try:
            if search:
                result = TbDrawing.objects.filter(Q(drawing_type__contains=search) | Q(creator__contains=search) |
                                                  Q(cutter__product_stage__contains=search) |
                                                  Q(cutter__type__cutter_type__contains=search)).exclude(is_delete=1)
            elif stage:
                result = TbDrawing.objects.filter(cutter_id=stage).exclude(is_delete=1)

            else:
                TbDrawing.objects.filter(id=1).update(modify_time=now)
                result = TbDrawing.objects.exclude(is_delete=1).order_by("-modify_time")

            if page_num:
                pag_class = Paginator(result, 20)
            else:
                pag_class = Paginator(result, len(result) + 1)
                page_num = 1
            select_data = pag_class.page(page_num)
            content["payload"] = {"data": [], "page": {}}

            if select_data:
                for i in select_data:
                    seal_id, seal_no, seal_name = [], [], []
                    seal_data = TbDrawingSeal.objects.filter(drawing_id=i.id)
                    # print(seal_data.values("seal_id","drawing_id"))
                    if seal_data:
                        for j in seal_data:
                            if j.seal_id:
                                seal_id.append(j.seal_id)
                                seal_no.append(j.seal.seal_no)
                                seal_name.append(j.seal.seal_name)
                    if i.cutter:
                        content["payload"]["data"].append({
                            "id": i.id, "drawing_type": i.drawing_type,
                            "creator": i.creator,
                            "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "stage": i.cutter.product_stage if i.cutter else None,
                            "seal_id_list": seal_id,
                            "seal_no": seal_no,
                            "seal_name": seal_name,
                            "stage_id": i.cutter.id if i.cutter else None,
                            "cutter_type": i.cutter.type.cutter_type if i.cutter.type else None,
                            "cutter_id": i.cutter.type.id if i.cutter.type else None,
                        })
                    else:
                        content["payload"]["data"].append({
                            "id": i.id, "drawing_type": i.drawing_type,
                            "creator": i.creator,
                            "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "stage": i.cutter.product_stage if i.cutter else None,
                            "seal_id_list": seal_id,
                            "seal_no": seal_no,
                            "seal_name": seal_name,
                            "stage_id": i.cutter.id if i.cutter else None,
                            "cutter_type": i.cutter.type.cutter_type if i.cutter else None,
                            "cutter_id": i.cutter.type.id if i.cutter else None,
                        })
            content["payload"]["page"] = {'count': pag_class.count, 'page': int(page_num),
                                          'page_number': pag_class.page_range[-1]}
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def drawing_type(request, pk):
    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        result = TbDrawing.objects.filter(id=pk).exclude(is_delete=1)
        # print(result)
        if result:
            for i in result:

                seal_id, seal_no, seal_name = [], [], []
                seal_data = TbDrawingSeal.objects.filter(drawing_id=i.id)
                if seal_data:
                    for j in seal_data:
                        seal_id.append(j.seal_id)
                        seal_no.append(j.seal.seal_no if j.seal else None)
                        seal_name.append(j.seal.seal_name if j.seal else None)
                if i.cutter:
                    content["payload"].append({
                        "id": i.id, "drawing_type": i.drawing_type,
                        "creator": i.creator,
                        "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "stage": i.cutter.product_stage if i.cutter else None,
                        "seal_id_list": seal_id,
                        "seal_no": seal_no,
                        "seal_name": seal_name,
                        "stage_id": i.cutter.id if i.cutter else None,
                        "cutter_type": i.cutter.type.cutter_type if i.cutter.type else None,
                        "cutter_id": i.cutter.type.id if i.cutter.type else None,
                    })
                else:
                    content["payload"].append({
                        "id": i.id, "drawing_type": i.drawing_type,
                        "creator": i.creator,
                        "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "stage": i.cutter.product_stage if i.cutter else None,
                        "seal_id_list": seal_id,
                        "seal_no": seal_no,
                        "seal_name": seal_name,
                        "stage_id": i.cutter.id if i.cutter else None,
                        "cutter_type": i.cutter.type.cutter_type if i.cutter else None,
                        "cutter_id": i.cutter.type.id if i.cutter else None,
                    })
    elif request.method == "PUT":
        content = {"payload": [], "status": 1, "errmsg": None}
        user = request.user.username + "(" + request.user.last_name + ")"
        try:
            data = request.data
            last_name = TbDrawing.objects.exclude(id=pk)
            stage = TbProdectStarge.objects.filter(id=data["stage_id"])[0].id
            for i in last_name:
                if data["drawing_type"] == i.drawing_type and i.cutter_id == stage:
                    content["errmsg"] = "提交名字已經存在，請重新命名！"
                    content["status"] = 0
                    return Response(content)
            seal_id_list = eval(data["seal_id_list"])
            if not seal_id_list:
                content["errmsg"] = "請選擇電子印章！"
                content["status"] = 0
                return Response(content)

            TbDrawing.objects.filter(id=pk).exclude(is_customer=1).update(drawing_type=data["drawing_type"],
                                                                          cutter_id=data["stage_id"],
                                                                          )

            TbProdectStarge.objects.filter(id=data["stage_id"]).exclude(is_customer=1).update(type_id=data["cutter_id"])
            old_seal = set([i["seal_id"] for i in TbDrawingSeal.objects.filter(drawing_id=pk).values("seal_id")])
            new_seal = set([int(i) for i in eval(data["seal_id_list"])])
            the_same = old_seal & new_seal
            insert_seal = list(the_same ^ new_seal)
            delete_seal = list(the_same ^ old_seal)
            if insert_seal:
                inser_list = [TbDrawingSeal(seal_id=i, drawing_id=pk, create_time=now, creator=user) for i in
                              insert_seal]
                TbDrawingSeal.objects.bulk_create(inser_list)
            if delete_seal:
                for i in delete_seal:
                    TbDrawingSeal.objects.filter(seal_id=i, drawing_id=pk).delete()
            # TbDrawingSeal.objects.filter(seal_id__in=)
            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    elif request.method == "DELETE":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            is_custome = TbDrawing.objects.filter(id=pk).values_list("is_customer", flat=1)[0]
            if is_custome:
                content["errmsg"] = "客户图纸类别，无法删除！"
                content["status"] = 0
                return Response(content)

            seal_id = [i["seal_id"] for i in TbDrawingSeal.objects.filter(drawing_id=pk).values("seal_id")]
            TbDrawingFile.objects.filter(drawing_type_id=pk).update(drawing_type_id=None)
            for i in seal_id:
                TbDrawingSeal.objects.filter(seal_id=i, drawing_id=pk).delete()
            TbDrawing.objects.filter(id=pk).update(is_delete=1)
            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = "绑定关系，无法删除！"
            # content["errmsg"] = str(e)
            content["status"] = 0
    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def seals(request):
    """
    电子印章上传接口：\n
    1.POST:参数：drawing_id:所属的图纸类别 ,filename：电子印章图片，seal_name:电子印章名称，seal_size:大小，size_desc：详情
    :param request:
    :return:
    """

    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        search = request.GET.get("search", None)
        page_num = request.GET.get("page", None)
        try:
            if search:
                result = TbSeal.objects.filter(Q(seal_name__contains=search) | Q(creator__contains=search) |
                                               Q(seal_no__contains=search) | Q(seal_desc__contains=search) |
                                               Q(seal_size__contains=search))
            else:
                result = TbSeal.objects.all()

            content["payload"] = {"data": [], "page": {}}
            if page_num:
                pag_class = Paginator(result, 20)
                content["payload"]["page"] = {'count': pag_class.count, 'page': int(page_num),
                                              'page_number': pag_class.page_range[-1]}
                select_data = pag_class.page(page_num)
            else:

                select_data = result

            if select_data:
                for i in select_data:
                    content["payload"]["data"].append({
                        "id": i.id,
                        "seal_name": i.seal_name,
                        "seal_no": i.seal_no,
                        "seal_size": i.seal_size,
                        "seal_desc": i.seal_desc,
                        "seal_path": i.seal_href,
                        "creator": i.creator,
                        # "drawing_type": i.drawing.drawing_type,
                        # "drawing_id": i.drawing_id,
                        "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S")
                    })

        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    elif request.method == "POST":
        try:
            content = {"payload": [], "status": 1, "errmsg": None}
            user = request.user.username + "(" + request.user.last_name + ")"
            # file_name = request.FILES.get("file")
            last_name = TbSeal.objects.all()
            data = request.data
            for i in last_name:
                if data["seal_name"] == i.seal_name:
                    content["errmsg"] = "提交名字已經存在，請重新命名！"
                    content["status"] = 0
                    return Response(content)
            img_name = request.FILES.getlist('filename')
            image = str(img_name[0]).split('.')
            uid = str(uuid.uuid1())
            name = uid + '.' + image[-1]
            path = os.path.join(settings.MEDIA_ROOT, settings.DRAWING_PATH, name)
            keep_path = os.path.join(settings.DRAWING_PATH, name)
            with open(path, 'wb') as flhd:
                flhd.write(img_name[0].read())
                flhd.close()
            size = Image.open(img_name[0]).size
            seal_size = str(int(size[0] * 10 / 25)) + "*" + str(int(size[1] * 10 / 25)) + "mm"
            TbSeal.objects.create(seal_name=data["seal_name"],
                                  seal_no=seal_num(),
                                  # drawing_id=data["drawing_id"],
                                  seal_size=seal_size,
                                  seal_desc=data["seal_desc"],
                                  seal_href=keep_path,
                                  creator=user,
                                  create_time=now, )
            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def seal(request, pk):
    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        result = TbSeal.objects.filter(id=pk)
        if result:
            for i in result:
                content["payload"].append({
                    "id": i.id,
                    "seal_name": i.seal_name,
                    "seal_no": i.seal_no,
                    "seal_size": i.seal_size,
                    "seal_desc": i.seal_desc,
                    "seal_path": i.seal_href,
                    "creator": i.creator,
                    # "drawing_type": i.drawing.drawing_type,
                    # "drawing_id": i.drawing_id,
                    "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S")
                })

    elif request.method == "PUT":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            user = request.user.username + "(" + request.user.last_name + ")"

            data = request.data
            last = TbSeal.objects.filter(id=pk)[0].seal_href
            last_name = TbSeal.objects.exclude(id=pk)
            for i in last_name:
                if data["seal_name"] == i.seal_name:
                    content["errmsg"] = "提交名字已經存在，請重新命名！"
                    content["status"] = 0
                    return Response(content)
            img_name = request.FILES.getlist('filename')
            if img_name:
                image = str(img_name[0]).split('.')
                uid = str(uuid.uuid1())
                name = uid + '.' + image[-1]
                path = os.path.join(settings.MEDIA_ROOT, settings.DRAWING_PATH, name)
                keep_path = os.path.join(settings.DRAWING_PATH, name)
                with open(path, 'wb') as flhd:
                    flhd.write(img_name[0].read())
                    flhd.close()
                size = Image.open(img_name[0]).size
                seal_size = str(int(size[0] * 10 / 25)) + "*" + str(int(size[1] * 10 / 25)) + "mm"
                TbSeal.objects.filter(id=pk).update(seal_href=keep_path)

                last_path = os.path.join(settings.MEDIA_ROOT, last)
                os.remove(last_path)
                TbSeal.objects.filter(id=pk).update(seal_name=data["seal_name"],
                                                    seal_size=seal_size,
                                                    seal_desc=data["seal_desc"],
                                                    # drawing_id=data["drawing_id"],
                                                    creator=user)
            else:
                TbSeal.objects.filter(id=pk).update(seal_name=data["seal_name"],
                                                    seal_desc=data["seal_desc"],
                                                    # drawing_id=data["drawing_id"],
                                                    creator=user)

            content["payload"] = "Success!"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
    elif request.method == "DELETE":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            TbDrawingSeal.objects.filter(seal_id=pk).update(seal_id=None)
            TbSeal.objects.filter(id=pk).delete()
            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def drawing_seals(request):
    """
    电子印章与图纸类别关联接口： \n
    1.GET: 传递参数relation 显示所有电子印章和图纸信息，不传relation参数显示已经关联好所有信息 \n
    2.POST : 传递 seal_id,drawing_type_id  \n
    :param request:
    :return:
    """
    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        relation = request.GET.get("relation")
        if relation:
            content["payload"] = {"seal": [], "drawing_type": []}
            seal_data = TbSeal.objects.all()
            drawing_data = TbDrawing.objects.all()
            if seal_data:
                for i in seal_data:
                    content["payload"]["seal"].append({
                        "seal_id": i.id,
                        "seal_name": i.seal_name,
                        "seal_no": i.seal_no,
                        "seal_size": i.seal_size,
                        "seal_desc": i.seal_desc,
                        "seal_path": i.seal_href,
                    })
            if drawing_data:
                for i in drawing_data:
                    content["payload"]["drawing_type"].append({
                        "drawing_type_id": i.id,
                        "drawing_type": i.drawing_type,
                        "creator": i.creator,
                        "stage": i.cutter.product_stage,
                        "stage_id": i.cutter.id,
                        "cutter_type": i.cutter.type.cutter_type,
                        "cutter_id": i.cutter.type.id,
                    })
            return Response(content)
        result = TbDrawingSeal.objects.all()
        if result:
            for i in result:
                content["payload"].append({
                    "id": i.id,
                    "drawing_type": i.drawing.drawing_type,
                    "stage": i.drawing.cutter.product_stage,
                    "cutter_type": i.drawing.cutter.type.cutter_type,
                    "seal_no": i.seal.seal_no,
                    "seal_name": i.seal.seal_name,
                    "seal_href": i.seal.seal_href,
                    "creator": i.creator,
                    "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S")
                })
        return Response(content)

    elif request.method == "POST":
        content = {"payload": [], "status": 1, "errmsg": None}
        ds_data = request.data
        user = request.user.username + "(" + request.user.last_name + ")"
        seal_id = ds_data["seal_id"]
        try:
            TbDrawingSeal.objects.create(drawing_id=ds_data["drawing_type_id"],
                                         seal_id=ds_data["seal_id"],
                                         create_time=now,
                                         creator=user
                                         )
            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
        return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def drawing_seal(request, pk):
    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        result = TbDrawingSeal.objects.filter(id=pk)
        if result:
            for i in result:
                content["payload"].append({
                    "id": i.id,
                    "drawing_type": i.drawing.drawing_type,
                    "stage": i.drawing.cutter.product_stage,
                    "cutter_type": i.drawing.cutter.type.cutter_type,
                    "seal_no": i.seal.seal_no,
                    "seal_name": i.seal.seal_name,
                    "seal_href": i.seal.seal_href,
                    "creator": i.creator,
                    "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S")
                })

    elif request.method == "PUT":
        content = {"payload": [], "status": 1, "errmsg": None}
        user = request.user.username + "(" + request.user.last_name + ")"
        try:
            ds_data = request.data
            TbDrawingSeal.objects.filter(id=pk).update(drawing_id=ds_data["drawing_type_id"],
                                                       seal_id=ds_data["seal_id"], creator=user)
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    elif request.method == "DELETE":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            TbSeal.objects.filter(id=pk).delete()
            content["payload"] = "Success"
        except Exception as e:
            content["errmsg"] = "绑定关系，无法删除！"
            content["status"] = 0

    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def message_list(request):
    if request.method == "GET":
        content = {"payload": {"data": [], "page": {}}, "status": 1, "errmsg": None}
        try:
            page_num = request.GET.get("page", None)
            search = request.GET.get("search", None)  # 先做ecn_no搜索
            type = request.GET.get("type", None)
            # try:
            #     result_cut = TbApplyform.objects.filter(customer__c_confirm=1,
            #                                             wrecord__workflowapprovalrecord__approver=request.user).all()
            #
            #     result_pro = TbApplyform.objects.filter(project__p_confirm=1,
            #                                             wrecord__workflowapprovalrecord__approver=request.user).all()
            # except:
            #     result_cut, result_pro = [], []
            try:
                if type == "0":  # 我的未签核

                    if search:
                        result_cut = TbApplyform.objects.exclude(customer__c_confirm=0).filter(
                            customer__c_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__status=0,
                            wrecord__workflowapprovalrecord__approver=request.user).filter(
                            Q(customer__ecn_no__contains=search) | Q(
                                wrecord__workflowapprovalrecord__approver__contains=search) |
                            Q(customer__case_name__contains=search) | Q(customer__custters_spec__contains=search)).all()
                        result_pro = TbApplyform.objects.exclude(project__p_confirm=0).filter(
                            project__p_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__status=0,
                            wrecord__workflowapprovalrecord__approver=request.user).filter(
                            Q(project__ecn_no__contains=search) | Q(
                                wrecord__workflowapprovalrecord__approver__contains=search) |
                            Q(project__case_no__contains=search) | Q(project__custters_spec__contains=search)).all()
                    else:
                        result_cut = TbApplyform.objects.exclude(customer__c_confirm=0).filter(
                            customer__c_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__status=0,
                            wrecord__workflowapprovalrecord__approver=request.user).all()
                        # print(result_cut)
                        result_pro = TbApplyform.objects.exclude(project__p_confirm=0).filter(
                            project__p_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__status=0,
                            wrecord__workflowapprovalrecord__approver=request.user).all()

                elif type == "1":  # 我发起的
                    if search:
                        result_cut = TbApplyform.objects.exclude(customer__c_confirm=0).filter(
                            customer__c_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__action="發起",
                            wrecord__applicant=request.user).filter(
                            Q(customer__ecn_no__contains=search) | Q(
                                wrecord__workflowapprovalrecord__approver__contains=search) |
                            Q(customer__case_name__contains=search) | Q(customer__custters_spec__contains=search)).all()
                        result_pro = TbApplyform.objects.exclude(project__p_confirm=0).filter(
                            project__p_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__action="發起",
                            applicant=request.user).filter(
                            Q(project__ecn_no__contains=search) | Q(
                                wrecord__workflowapprovalrecord__approver__contains=search) |
                            Q(project__case_no__contains=search) | Q(project__custters_spec__contains=search)).all()
                    else:
                        result_cut = TbApplyform.objects.exclude(customer__c_confirm=0).filter(
                            customer__c_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__action="發起",
                            wrecord__applicant=request.user).all()
                        result_pro = TbApplyform.objects.exclude(project__p_confirm=0).filter(
                            project__p_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__action="發起",
                            wrecord__applicant=request.user).all()

                elif type == "2":  # 我的已签核
                    if search:
                        result_cut = TbApplyform.objects.exclude(customer__c_confirm=0).filter(
                            customer__c_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__approver=request.user,
                            wrecord__workflowapprovalrecord__status=1).filter(
                            Q(customer__ecn_no__contains=search) | Q(
                                wrecord__workflowapprovalrecord__approver__contains=search) |
                            Q(customer__case_name__contains=search) | Q(
                                customer__custters_spec__contains=search)).distinct()
                        result_pro = TbApplyform.objects.exclude(project__p_confirm=0).filter(
                            project__p_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__status=1,
                            wrecord__workflowapprovalrecord__approver=request.user).filter(
                            Q(project__ecn_no__contains=search) | Q(
                                wrecord__workflowapprovalrecord__approver__contains=search) |
                            Q(project__case_no__contains=search) | Q(
                                project__custters_spec__contains=search)).distinct()

                    else:
                        result_cut = TbApplyform.objects.exclude(customer__c_confirm=0).filter(
                            customer__c_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__status=1,
                            wrecord__workflowapprovalrecord__approver=request.user).distinct()
                        result_pro = TbApplyform.objects.exclude(project__p_confirm=0).filter(
                            project__p_confirm__range=[-1, 3],
                            wrecord__workflowapprovalrecord__status=1,
                            wrecord__workflowapprovalrecord__approver=request.user).distinct()
            except:
                result_cut, result_pro = [], []

            from tb_forms import models
            if result_cut:

                for i in result_cut:
                    approval = []
                    for j, row in enumerate(i.wrecord.workflowapprovalrecord_set.values_list("status", flat=1)):
                        if row == "0":

                            job_nu = i.wrecord.workflowapprovalrecord_set.values_list("approver", flat=1)[j]
                            if job_nu:
                                name = models.TbUser.objects.filter(username=job_nu).values_list("last_name", flat=1)[0]
                                job_nu = job_nu + "(" + name + ")"
                            approval.append(job_nu)
                    content["payload"]["data"].append({
                        "confirm": i.customer.c_confirm,
                        "next_to": approval if approval else "已簽核",
                        "modify_time": i.wrecord.workflowapprovalrecord_set.values_list("end_time", flat=1)[0].strftime(
                            "%Y-%m-%d %H:%M:%S") if type == "2" else i.apply_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "create_time": i.apply_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "approver": i.applicant + "(" +
                                    models.TbUser.objects.filter(username=i.applicant).values_list("last_name",
                                                                                                   flat=1)[
                                        0] + ")",
                        "wrecord_id": i.wrecord_id,
                        "id": i.customer_id,
                        "type": "customer",
                        "case": i.customer.case_name,
                        "ecn_no": i.card_id,
                        "priority": i.customer.priority,
                        "cutter_spec": i.customer.custters_spec,
                        "version": i.customer.version
                    })
            if result_pro:
                for i in result_pro:
                    approval = []
                    for j, row in enumerate(i.wrecord.workflowapprovalrecord_set.values_list("status", flat=1)):
                        if row == "0":
                            job_nu = i.wrecord.workflowapprovalrecord_set.values_list("approver", flat=1)[j]
                            if job_nu:
                                name = models.TbUser.objects.filter(username=job_nu).values_list("last_name", flat=1)[0]
                                job_nu = job_nu + "(" + name + ")"
                            approval.append(job_nu)

                    content["payload"]["data"].append({
                        "confirm": i.project.p_confirm,
                        "next_to": approval if approval else "已簽核",
                        "create_time": i.apply_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "modify_time": i.wrecord.workflowapprovalrecord_set.values_list("end_time", flat=1)[
                            0].strftime(
                            "%Y-%m-%d %H:%M:%S") if type == "2" else i.apply_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "wrecord_id": i.wrecord_id,
                        "type": "project",
                        "approver": i.applicant + "(" +
                                    models.TbUser.objects.filter(username=i.applicant).values_list("last_name",
                                                                                                   flat=1)[
                                        0] + ")",
                        "id": i.project_id,
                        "case": i.project.case_no,
                        "ecn_no": i.card_id,
                        "cutter_spec": i.project.custters_spec,
                        "priority": i.project.priority,
                        "version": i.project.version

                    })

            result = content["payload"]["data"]
            result = sorted(result, key=lambda result: result["create_time"], reverse=1)  # 按照时间倒叙
            if page_num:
                pag_class = Paginator(result, 20)
            else:
                pag_class = Paginator(result, len(result) + 1)
                page_num = 1
            content["payload"]["page"] = {'count': pag_class.count, 'page': int(page_num),
                                          'page_number': pag_class.page_range[-1]}
            content["payload"]["data"] = (list(pag_class.page(page_num)))
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
        return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def dispense(request):
    """
        acceptor:接收人列表(工号列表如["F123"])
        project_id :工程图纸信息的id没有不传值
        customer_id :客户图纸信息的id没有不传值
        drawing_type_id : 图纸文件id列表[]

    :param request:
    :return:
    """
    if request.method == "POST":
        content = {"payload": [], "status": 1, "errmsg": None}
        data = request.data
        try:
            user = request.user.username + "(" + request.user.last_name + ")"
            acceptor = data["acceptor"].split(",")
            project_id = int(data["project_id"]) if "project_id" in data.keys() else None
            customer_id = int(data["customer_id"]) if "customer_id" in data.keys() else None
            drawing_file_id = data["drawing_file_id"].split(",")
            depense_list = []
            # print(acceptor,drawing_file_id,customer_id)
            project_status = TbProjectPaper.objects.filter(id=project_id, enabled=0)
            customer_status = TbCustomerPaper.objects.filter(id=customer_id, enabled=0)
            if project_status or customer_status:
                content["errmsg"] = "圖紙已經失效不能分發！"
                content["status"] = 0
                return Response(content)

            with transaction.atomic():
                for peopele in acceptor:
                    if peopele == "":
                        content["errmsg"] = "存在空的接收人，不能分發！"
                        content["status"] = 0
                        return Response(content)
                    for file_id in drawing_file_id:
                        drawing = TbDrawingFile.objects.filter(id=file_id).values_list(
                            "drawing_type__cutter__type__cutter_type",
                            "drawing_type__cutter__product_stage")[0]
                        depense_list.append(TbDepense(accptor=peopele, project_id=project_id, customer_id=customer_id,
                                                      drawing_file_id=file_id, create_time=now, status=0,
                                                      distributor=user, product_type=drawing[0],
                                                      product_stage=drawing[1]))
                    from customer import models
                    from wfs import models as md
                    name = md.User.objects.filter(username=peopele).values_list("last_name",flat=1)[0]
                    to = peopele+"("+name+")"
                    if project_id:
                        models.TbProjectPaper.objects.filter(id=project_id).update(p_confirm=3)
                        url222 = "../templates/module1/index.html#/drawengcheck/:{}?action=receive".format(project_id)
                        form_id = project_id
                        pro_paper = models.TbProjectPaper.objects.filter(id=project_id)[0]
                        ecn = pro_paper.ecn_no
                        paper_name = pro_paper.case_name
                        create_time = pro_paper.create_time
                        sql = pro_paper.custters_spec + pro_paper.stage_type + pro_paper.cutter_type + pro_paper.version
                        url = "drawengcheck/:{}".format(pro_paper.id)
                        forms = "drawengreceive"

                        ttt = "【工程圖紙接收】您有工程圖紙需要接收"
                        if models.TbProjectPaper.objects.filter(id_copy=project_id):
                            title = "【接收通知】"
                            type = "工程圖紙"
                        else:
                            title = "【變更通知】"
                            type = "工程變更圖紙"
                    if customer_id:
                        models.TbCustomerPaper.objects.filter(id=customer_id).update(c_confirm=3)
                        url222 = "../templates/module1/index.html#/drawcuscheck/:{}?action=receive".format(customer_id)
                        form_id = customer_id
                        cust_paper = models.TbCustomerPaper.objects.filter(id=customer_id)[0]
                        paper_name = cust_paper.case_name
                        create_time = cust_paper.create_time
                        ecn = cust_paper.ecn_no
                        sql = cust_paper.custters_spec + cust_paper.p_name + cust_paper.version
                        url = "drawcuscheck/:{}".format(cust_paper.id)
                        forms = "drawcusreceive"
                        ttt = "【客戶圖紙接收】您有客戶圖紙需要接收"
                        if models.TbCustomerPaper.objects.filter(copy_id=customer_id):
                            title = "【接收通知】"
                            type = "客戶圖紙"
                        else:
                            title = "【變更通知】"
                            type = "客戶變更圖紙"
                    mailtototot(peopele, title, type, sql, url,forms)
                    action = "ok"
                    cuidan = {'type': 'qianhe',
                              'from': user,
                              'to': to, 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                              'message': {'no': ecn, 'type': "簽單動態", 'time': "2017-06-27 11:55:08",
                                          'title': ttt,
                                          'url': url222},
                              'content': [{'form_id': form_id, 'form_no': ecn,
                                           'form_name': paper_name,
                                           'initial_date': create_time.strftime('%Y-%m-%d %H:%M:%S'),
                                           'current_approver': "",
                                           'current_approve_date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                           'current_approve_status':action, 'current_approve_comment':"",
                                           'next_approver': to, 'status': 'open'}]}
                    log = ReminderLog.objects.create(no=ecn, rectime=datetime.datetime.now(),
                                                     applicant=request.user.username,
                                                     user=to,
                                                     name=request.user.last_name,
                                                     title=cuidan['message']['title'],
                                                     type=cuidan['message']['type'], url=cuidan['message']['url'],
                                                     status=0)
                    cuidan['message']['id'] = log.id
                    message = threading.Thread(target=cccc, args=(str(cuidan)))
                    message.setDaemon(True)
                    message.start()

                for file_id in drawing_file_id:
                    file_type = TbDrawingFile.objects.filter(id=file_id).values_list("file_type", "file_path")[0]
                    if file_type[0]:  # 文件类别为附件

                        TbDrawingFile.objects.filter(id=file_id).update(seal_filepath=file_type[1])
                    else:  # 文件类别为图纸
                        dra_id = TbDrawingFile.objects.filter(id=file_id).values_list("drawing_type_id",
                                                                                      flat=True)[0]
                        if dra_id:
                            seal_href = TbDrawingSeal.objects.filter(drawing_id=dra_id).values_list("seal__seal_href",
                                                                                                    flat=True)
                        else:
                            seal_href = TbDrawingSeal.objects.filter(drawing_id=1).values_list("seal__seal_href",
                                                                                               flat=True)
                        seal_href = [x for x in seal_href if x]
                        sign_filepath = \
                            TbDrawingFile.objects.filter(id=file_id).values_list("file_path", flat=True)[0]
                        if not sign_filepath:
                            content["errmsg"] = "簽核圖紙未找到!"
                            content["status"] = 0
                            return Response(content)
                        pdf_path = settings.MEDIA_ROOT + sign_filepath
                        seal_path = [settings.MEDIA_ROOT + i for i in seal_href]

                        # name = gai_zhang(pdf_path, seal_path, settings.MEDIA_ROOT + settings.DRAWING_PATH)
                        name = seal_pdf(pdf_path, seal_path)
                        TbDrawingFile.objects.filter(id=file_id).update(seal_filepath=name.split("ST/")[-1])

                TbDepense.objects.bulk_create(depense_list)


        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    if request.method == "GET":
        content = {"payload": {"data": [], "page": {}}, "status": 1, "errmsg": None}
        try:
            customer_id = request.GET.get("customer_id", None)
            project_id = request.GET.get("project_id", None)
            page_num = request.GET.get("page", None)
            status = request.GET.get("type", 0)
            search = request.GET.get("search", "")
            result = None
            if customer_id:
                result = TbDepense.objects.filter(customer_id=int(customer_id))
                if not result:
                    return Response(content)


            elif project_id:
                result = TbDepense.objects.filter(project_id=project_id)
                if not result:
                    return Response(content)

            if result:
                for i in result:

                    from tb_forms.models import TbUser, TbUserOrg, TbOrg
                    usr_message = TbUser.objects.filter(username=i.accptor, status_id=100).values_list('username',
                                                                                                       'tbuserorg__org__org_code',
                                                                                                       'tbuserorg__org__org_name',
                                                                                                       'last_name')
                    dra = TbDrawingFile.objects.filter(id=i.drawing_file_id).values_list("drawing_type_id", "file_name",
                                                                                         "drawing_type__cutter__type__cutter_type",
                                                                                         "dev_type"
                                                                                         )[0]
                    dra_id = dra[0]

                    if dra_id:
                        seal_no = TbDrawingSeal.objects.filter(drawing_id=dra_id).values_list("seal__seal_no",
                                                                                              flat=True)
                        seal_href = TbDrawingSeal.objects.filter(drawing_id=dra_id).values_list("seal__seal_href",
                                                                                                flat=True)
                    else:
                        seal_no, seal_href = [], []

                    content["payload"]["data"].append({
                        "id": i.id,
                        "acceptor": i.accptor + "(" + usr_message[0][-1] + ")",
                        "org_code": usr_message[0][1],
                        "org_name": usr_message[0][2],
                        "customer_id": i.customer_id,
                        # "project_id": i.project_id,
                        'seal_no': seal_no,
                        "seal_href": seal_href,
                        "distributor": i.distributor,
                        "status": i.status,
                        "drawing_file_id": i.drawing_file_id,
                        "file_name": dra[1],
                        "dev_type": dra[3],
                        'drawing_type': dra[2],
                        "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S")
                    })

                return Response(content)
            else:
                # cust_id = TbDepense.objects.values_list("customer_id",flat=1).distinct()
                # pro_id = TbDepense.objects.values_list("project_id",flat=1).distinct()
                if int(status):
                    result_cu = TbCustomerPaper.objects.filter(c_confirm=3)
                    result_pro = TbProjectPaper.objects.filter(p_confirm=3)
                    if search:
                        result_cu = TbCustomerPaper.objects.filter(c_confirm=3).filter(
                            Q(case_name__contains=search) | Q(p_name__contains=search))
                        result_pro = TbProjectPaper.objects.filter(p_confirm=3).filter(
                            Q(case_name__contains=search) | Q(stage_type__contains=search) | Q(
                                cutter_type__contains=search))
                else:
                    result_cu = TbCustomerPaper.objects.filter(c_confirm=2, enabled=1)
                    result_pro = TbProjectPaper.objects.filter(p_confirm=2, enabled=1)
                    if search:
                        result_cu = TbCustomerPaper.objects.filter(c_confirm=2, enabled=1).filter(
                            Q(case_name__contains=search) | Q(p_name__contains=search))
                        result_pro = TbProjectPaper.objects.filter(p_confirm=2, enabled=1).filter(
                            Q(case_name__contains=search) | Q(stage_type__contains=search) | Q(
                                cutter_type__contains=search))
                if result_cu:
                    for i in result_cu:
                        product = TbDrawingFile.objects.filter(customer_id=i.id).all()
                        if product:
                            product_id = product[0].drawing_type_id
                            if product_id:
                                product_type = \
                                TbDrawing.objects.filter(id=product_id).values_list("cutter__type__cutter_type",
                                                                                    flat=1)[0]
                                product_stage = \
                                TbDrawing.objects.filter(id=product_id).values_list("cutter__product_stage",
                                                                                    flat=1)[0]
                        else:
                            product_type, product_stage = None, None
                        content["payload"]["data"].append({
                            "id": i.id,
                            "ecn_no": i.ecn_no,
                            "cutter_spec": i.custters_spec,
                            "case_name": i.case_name,
                            "priority": i.priority,
                            "create_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "version": i.version,
                            "type": "customer",
                            "product_type": product_type if product_type else "-",
                            "product_stage": product_stage if product_stage else "-",
                        })
                if result_pro:
                    for i in result_pro:
                        product = TbDrawingFile.objects.filter(project_id=i.id).all()
                        if product:
                            product_id = product[0].drawing_type_id
                            if product_id:
                                product_type = \
                                    TbDrawing.objects.filter(id=product_id).values_list("cutter__type__cutter_type",
                                                                                        flat=1)[0]
                                product_stage = \
                                    TbDrawing.objects.filter(id=product_id).values_list("cutter__product_stage",
                                                                                        flat=1)[0]
                        # # print(product_type,product_stage)
                        else:
                            product_type, product_stage = None, None
                        content["payload"]["data"].append({
                            "id": i.id,
                            "ecn_no": i.ecn_no,
                            "cutter_spec": i.custters_spec,
                            "case_name": i.case_name,
                            "priority": i.priority,
                            "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "version": i.version,
                            "type": "project",
                            "product_type": product_type if product_type else "-",
                            "product_stage": product_stage if product_stage else "-",
                        })
                result = content["payload"]["data"]
                result = sorted(result, key=lambda result: result["create_time"], reverse=1)
            if page_num:
                pag_class = Paginator(result, 20)
            else:
                pag_class = Paginator(result, len(result) + 1)
                page_num = 1
            content["payload"]["page"] = {'count': pag_class.count, 'page': int(page_num),
                                          'page_number': pag_class.page_range[-1]}
            content["payload"]["data"] = (list(pag_class.page(page_num)))


        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def dispens(request, pk):
    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        result = TbDepense.objects.filter(id=pk).all()
        if result:
            for i in result:
                content["payload"].append({
                    "id": i.id,
                    "acceptor": i.accptor,
                    "customer_id": i.customer_id,
                    "project_id": i.project_id,
                    "distributor": i.distributor,
                    "status": i.status,
                    "drawing_file_id": i.drawing_file_id,
                    "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S")
                })
    elif request.method == "PUT":
        content = {"payload": [], "status": 1, "errmsg": None}
        TbDepense.objects.filter(id=pk).update(status=1)


    elif request.method == "DELETE":
        content = {"payload": [], "status": 1, "errmsg": None}
        if TbDepense.objects.filter(id=pk, status=1):
            content["errmsg"] = "文件已經接受，無法取消！"
            content["status"] = 0
            return Response(content)

        TbDepense.objects.filter(id=pk, status=0).delete()

    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def printings(request):
    """
            project_id :工程图纸信息的id没有不传值
            customer_id :客户图纸信息的id没有不传值

    :param request:
    :return:
    """

    if request.method == "POST":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            name = request.user.last_name
            user = request.user.username + "(" + name + ")"
            data = request.data
            project_id = data["project_id"] if "project_id" in data.keys() else None
            customer_id = data["customer_id"] if "customer_id" in data.keys() else None
            drawing_file_id = data["drawing_file_id"].split(",")
            reason = data["reason"] if "reason" in data.keys() else None
            print_no = data["print_no"]
            try:
                int(print_no)
            except:
                content["errmsg"] = "申請份數必須為阿拉伯數字，請重新輸入！"
                content["status"] = 0
                return Response(content)
            # for file_id in drawing_file_id:
            #     last = TbPrinting.objects.filter(drawing_file_id=file_id, project_id=project_id,
            #                                      customer_id=customer_id, sponsor=user)
            #     if last:
            #         content["errmsg"] = "圖紙已經申請過列印！"
            #         content["status"] = 0
            #         return Response(content)
            dispensing = "文控"
            project_status = TbProjectPaper.objects.filter(id=project_id, enabled=0)
            customer_status = TbCustomerPaper.objects.filter(id=customer_id, enabled=0)
            if project_status or customer_status:
                content["errmsg"] = "圖紙已經失效不能列印！"
                content["status"] = 0
                return Response(content)
            for file_id in drawing_file_id:
                drawing = TbDrawingFile.objects.filter(id=file_id).values_list(
                    "drawing_type__cutter__type__cutter_type",
                    "drawing_type__cutter__product_stage")[0]
                TbPrinting.objects.create(project_id=project_id, customer_id=customer_id, create_time=now,
                                          print_no=print_no, recycling_no=0,
                                          drawing_file_id=file_id, print_status=0, sponsor=user,
                                          dispensing=dispensing, reason=reason, product_type=drawing[0],
                                          product_stage=drawing[1])

        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
        return Response(content)

    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        usr = request.user
        try:
            # printing_data()
            start = request.GET.get('start')
            end = request.GET.get("end")
            page_num = request.GET.get("page", None)
            download = request.GET.get("download", None)
            customer_id = request.GET.get("customer_id", 0)
            project_id = request.GET.get("project_id", 0)
            status = request.GET.get("status", 0)
            search = request.GET.get("search", "")
            if customer_id:
                result = TbPrinting.objects.filter(customer_id=customer_id, sponsor__contains=request.user)
                if result:
                    for i in result:
                        file = \
                            TbDrawingFile.objects.filter(id=i.drawing_file_id).values_list("file_name",
                                                                                           "seal_filepath",
                                                                                           "drawing_type__drawing_type",
                                                                                           "drawing_type__cutter__product_stage")[
                                0]
                        status = TbCustomerPaper.objects.filter(id=i.id, copy_id=i.id)
                        if status:
                            customer_status = "發行"
                        else:
                            customer_status = "變更"

                        content["payload"].append({
                            "id": i.id,
                            "print_no": i.print_no,
                            "signer": i.signer,
                            "type": "customer",
                            "status": customer_status,
                            "file_name": file[0],
                            "file_path": file[1],
                            "product_type": file[2],
                            "product_stage": file[-1],
                            "recycling_no": i.recycling_no,
                            "print_status": i.print_status,
                            "sponsor": i.sponsor,
                            "dispensing": i.dispensing,
                            "customer_id": i.customer_id,
                            "case_name": i.customer.case_name,
                            "drawing_type": i.customer.drawing_type,
                            "custters_spec": i.customer.custters_spec,
                            "version": i.customer.version,
                            "ecn_no": i.customer.ecn_no,
                            "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "reason": i.reason
                        })
                return Response(content)

            if project_id:
                result = TbPrinting.objects.filter(project_id=project_id, sponsor__contains=request.user)
                if result:
                    for i in result:
                        file = \
                            TbDrawingFile.objects.filter(id=i.drawing_file_id).values_list("file_name",
                                                                                           "seal_filepath",
                                                                                           "drawing_type__drawing_type",
                                                                                           "drawing_type__cutter__product_stage")[
                                0]
                        status = TbProjectPaper.objects.filter(id=i.id, id_copy=i.id)

                        if status:
                            project_status = "變更"

                        else:
                            project_status = "發行"
                        # print(i.project.drawing_type)
                        content["payload"].append({
                            "id": i.id,
                            "print_no": i.print_no,
                            "signer": i.signer,
                            "type": "project",
                            "status": project_status,
                            "file_name": file[0],
                            "file_path": file[1],
                            "product_type": file[2],
                            "product_stage": file[-1],
                            "recycling_no": i.recycling_no,
                            "print_status": i.print_status,
                            "sponsor": i.sponsor,
                            "dispensing": i.dispensing,
                            "project_id": i.project_id,
                            "cutter_type": i.project.cutter_type,
                            "case_name": i.project.case_no,
                            "ecn_no": i.project.ecn_no,
                            "drawing_type": i.project.drawing_type,
                            "custters_spec": i.project.custters_spec,
                            "version": i.project.version,
                            "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "reason": i.reason
                        })
                return Response(content)

            # if start and end:
            #     start_time = datetime.datetime.strptime(start, "%Y-%m-%d")
            #     end_time = datetime.datetime.strptime(end, "%Y-%m-%d")
            #     result = TbPrinting.objects.filter(create_time__range=(start_time, end_time))
            result = TbPrinting.objects.all()
            if int(status):
                result = TbPrinting.objects.filter(recycling_no__gt=0)
                if search:
                    result = TbPrinting.objects.filter(recycling_no__gt=0).filter(Q(product_stage__contains=search) |
                                                                                  Q(product_type__contains=search))
            elif status == "0":
                result = TbPrinting.objects.filter(recycling_no=0)
                if search:
                    result = TbPrinting.objects.filter(recycling_no=0).filter(Q(product_stage__contains=search) |
                                                                                  Q(product_type__contains=search))
            elif search:
                result = TbPrinting.objects.filter(Q(product_stage__contains=search) |
                                                   Q(product_type__contains=search))

            content["payload"] = {"data": [], "page": {}}
            if result:
                for i in result:
                    if TbDrawingFile.objects.filter(id=i.drawing_file_id):
                        file = \
                            TbDrawingFile.objects.filter(id=i.drawing_file_id).values_list(
                                "file_name", "seal_filepath",
                                "drawing_type__drawing_type",
                                "drawing_type__cutter__product_stage")[
                                0]
                    else:
                        file = [None, None, None]
                    if i.customer_id:
                        if TbCustomerPaper.objects.filter(id=i.customer_id, enabled=0) and i.print_status:
                            continue
                        status = TbCustomerPaper.objects.filter(id=i.customer_id, copy_id=i.customer_id)
                        # print(i.customer_id, status)
                        if status:
                            customer_status = "發行"
                        else:
                            customer_status = "變更"
                        content["payload"]["data"].append({
                            "id": i.id,
                            "print_no": i.print_no,
                            "signer": i.signer,
                            "type": "customer",
                            "status": customer_status,
                            "recycling_no": i.recycling_no,
                            "print_status": i.print_status,
                            "sponsor": i.sponsor,
                            "file_name": file[0],
                            "file_path": file[1],
                            "product_type": file[2],
                            "product_stage": file[-1],
                            "dispensing": i.dispensing,
                            "customer_id": i.customer_id,
                            "case_name": i.customer.case_name,
                            "drawing_type": i.customer.drawing_type,
                            "custters_spec": i.customer.custters_spec,
                            "version": i.customer.version,
                            "ecn_no": i.customer.ecn_no,
                            "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "reason": i.reason
                        })
                    elif i.project_id:
                        if TbProjectPaper.objects.filter(id=i.project_id, enabled=0) and i.print_status:
                            continue
                        status = TbProjectPaper.objects.filter(id=i.project_id, id_copy=i.project_id)
                        if status:
                            project_status = "發行"
                        else:
                            project_status = "變更"
                        content["payload"]["data"].append({
                            "id": i.id,
                            "print_no": i.print_no,
                            "signer": i.signer,
                            "type": "project",
                            "status": project_status,
                            "file_name": file[0],
                            "file_path": file[1],
                            "product_type": file[2],
                            "product_stage": file[-1],
                            "recycling_no": i.recycling_no,
                            "print_status": i.print_status,
                            "sponsor": i.sponsor,
                            "dispensing": i.dispensing,
                            "project_id": i.project_id,
                            "cutter_type": i.project.cutter_type,
                            "case_name": i.project.case_no,
                            "ecn_no": i.project.ecn_no,
                            "drawing_type": i.project.drawing_type,
                            "custters_spec": i.project.custters_spec,
                            "version": i.project.version,
                            "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "reason": i.reason
                        })
            result = content["payload"]["data"]
            result = sorted(result, key=lambda result: result["modify_time"], reverse=1)
            if download:
                content["payload"] = {}
                content["payload"]["path"] = print_download(result, TEMP_FILE)
                return Response(content)

            if page_num:
                pag_class = Paginator(result, 20)
            else:
                pag_class = Paginator(result, len(result) + 1)
                page_num = 1
            content["payload"]["page"] = {'count': pag_class.count, 'page': int(page_num),
                                          'page_number': pag_class.page_range[-1]}
            content["payload"]["data"] = (list(pag_class.page(page_num)))

        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

        return Response(content)

    elif request.method == "PUT":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            print_id = request.data["print_list"].split(",")
            if not print_id[0]:
                content["errmsg"] = "請選擇列印！"
                content["status"] = 0
                return Response(content)
            for i in print_id:
                TbPrinting.objects.filter(id=int(i)).update(print_status=1)
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
        return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def printing(request, pk):
    """
    修改用PUT:
        1.recycling_no:回收數量，
        2.signer：回收者
    :param request:
    :param pk:
    :return:
    """
    if request.method == "DELETE":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            # data = request.data
            # recycling_no = data["recycling_no"]
            # signer = data["signer"]
            if TbPrinting.objects.filter(id=pk, print_status=1):
                content["errmsg"] = "已經列印，無法取消！"
                content["status"] = 0
                return Response(content)

            TbPrinting.objects.filter(id=pk).delete()
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    if request.method == "PUT":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            data = request.data
            if "print_status" in data.keys():
                print_status = data["print_status"]
                if print_status:
                    TbPrinting.objects.filter(id=pk).update(print_status=1)
                    return Response(content)
            try:
                recycling_no = int(data["recycling_no"])
            except:
                content["errmsg"] = "回收份數有誤，請重新維護！"
                content["status"] = 0
                return Response(content)
            signer = request.user.username + "(" + request.user.last_name + ")"
            last = TbPrinting.objects.filter(id=pk).values_list("print_no", "recycling_no")[0]
            if last[1]:
                recycling_no = int(last[1]) + recycling_no
            if last[0] < recycling_no or recycling_no <= 0:
                content["errmsg"] = "回收份數有誤，請重新維護！"
                content["status"] = 0
                return Response(content)
            TbPrinting.objects.filter(id=pk).update(recycling_no=recycling_no, signer=signer)
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
            return Response(content)

    if request.method == "GET":
        content = {"payload": [], "status": 1, "errmsg": None}
        result = TbPrinting.objects.filter(id=pk)
        if result:
            for i in result:
                file = \
                    TbDrawingFile.objects.filter(id=i.drawing_file_id).values_list("file_name", "seal_filepath",
                                                                                   "drawing_type__drawing_type",
                                                                                   "drawing_type__cutter__product_stage")[
                        0]
                if i.customer_id:
                    content["payload"] = {
                        "id": i.id,
                        "print_no": i.print_no,
                        "signer": i.signer,
                        "type": "customer",
                        "file_name": file[0],
                        "file_path": file[1],
                        "product_stage": file[-1],
                        "product_type": file[2],
                        "recycling_no": i.recycling_no,
                        "print_status": i.print_status,
                        "sponsor": i.sponsor,
                        "dispensing": i.dispensing,
                        "customer_id": i.customer_id,
                        "case_name": i.customer.case_name,
                        "drawing_type": i.customer.drawing_type,
                        "custters_spec": i.customer.custters_spec,
                        "version": i.customer.version,
                        "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "reason": i.reason
                    }
                elif i.project_id:
                    content["payload"] = {
                        "id": i.id,
                        "print_no": i.print_no,
                        "signer": i.signer,
                        "type": "project",
                        "file_name": file[0],
                        "file_path": file[1],
                        "product_stage": file[-1] if file[-1] else "-",
                        "product_type": file[2],
                        "recycling_no": i.recycling_no,
                        "print_status": i.print_status,
                        "sponsor": i.sponsor,
                        "dispensing": i.dispensing,
                        "project_id": i.project_id,
                        "cutter_type": i.project.cutter_type,
                        "case_name": i.project.case_no,
                        "drawing_type": i.project.drawing_type,
                        "custters_spec": i.project.custters_spec,
                        "version": i.project.version,
                        "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "modify_time": i.modify_time.strftime("%Y-%m-%d %H:%M:%S"),
                        "reason": i.reason
                    }
    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def accept(request):
    if request.method == "GET":
        content = {"payload": {"data": [], "page": {}}, "status": 1, "errmsg": None}
        try:

            customer_id_111 = request.GET.get("customer_id", None)
            project_id_222 = request.GET.get("project_id", None)
            paper_type = request.GET.get("type", "customer")
            status = int(request.GET.get("status", 0))
            search = request.GET.get("search", "")

            page_num = request.GET.get("page", None)

            # 客戶圖紙詳情：
            if customer_id_111:
                from customer.models import TbCustomerPaper, TbCustomInfo
                cust_lsit, files, content["payload"] = [], [], {}
                cust_desc = TbCustomerPaper.objects.filter(id=customer_id_111)
                for i in cust_desc.values():
                    content["payload"] = {
                        'id': i['id'],
                        'ecn_no': i['ecn_no'],
                        'version': i['version'],
                        'p_name': i['p_name'],
                        'st_site': i['st_site'],
                        'definer_name': i['definer_name'],
                        'c_name': i['c_name'],
                        'c_type': i['c_type'],
                        'c_site': i['c_site'],
                        'custters_spec': i['custters_spec'],
                        'case_name': i['case_name'],
                        'priority': i['priority'],
                        'desc_file': i['desc_file'],
                        'create_time': (i['create_time']).strftime("%Y-%m-%d %H:%M:%S"),
                        'modify_time': (i['modify_time']).strftime("%Y-%m-%d %H:%M:%S"),
                        'c_confirm': i['c_confirm'],
                        'customer_info': i['customer_info_id'],
                        'copy_id': i['copy_id'],
                        "alter_cause": i["alter_cause"],
                        "alter_front": i["alter_front"],
                        "alter_later": i["alter_later"],
                        "enabled": bool(i["enabled"]),
                        "valid": bool(i["valid"]),
                        "file": None
                    }
                # print(content)

                file_lsit = TbDepense.objects.filter(customer_id=customer_id_111).values_list("drawing_file_id", flat=1)
                # print(file_lsit)
                all_file = TbDrawingFile.objects.filter(id__in=file_lsit)

                for k in all_file.values():
                    file_path = k['seal_filepath']

                    files.append({'id': k['id'], 'file_name': k['file_name'], 'file_size': k['file_size'],
                                  'file_path': file_path, 'uploader': k['uploader'],
                                  'create_time': k['create_time'].strftime("%Y-%m-%d %H:%M:%S"),
                                  'customer': k['customer_id'], 'file_type': k['file_type'],
                                  })
                content['payload']['file'] = files
                return Response(content)

            # 工程圖紙詳情：
            if project_id_222:
                from customer.models import TbProjectPaper
                pro_list, files, content["payload"] = [], [], {}
                pro_desc = TbProjectPaper.objects.filter(id=project_id_222)
                for i in pro_desc:
                    content["payload"] = {
                        'id': i.id,
                        'ecn_no': i.ecn_no,
                        'version': i.version,
                        'definer_name': i.definer_name,
                        'st_site': i.st_site,
                        'project_name': i.project_name,
                        'p_type': i.p_type,
                        'custters_spec': i.custters_spec,
                        'case_name': i.case_name,
                        'priority': i.priority,
                        'stage_type_id': i.id_stage_type,
                        'stage_type': i.stage_type,
                        'case_no': i.case_no,
                        'alter_cause': i.alter_cause,
                        'alter_front': i.alter_front,
                        'alter_later': i.alter_later,
                        'desc_file': i.desc_file,
                        'create_time': (i.create_time).strftime("%Y-%m-%d %H:%M:%S"),
                        # 'create_time':(i.create_time),
                        'modify_time': (i.modify_time).strftime("%Y-%m-%d %H:%M:%S"),
                        # 'modify_time':(i.modify_time),
                        'cutter_type_id': i.id_cutter_type,
                        'cutter_type': i.cutter_type,
                        'copy_id': i.id_copy,
                        'upload_time': (i.upload_time).strftime("%Y-%m-%d %H:%M:%S"),
                        # 'upload_time':(i.upload_time),
                        'uploader': i.uploader,
                        'p_confirm': i.p_confirm,
                        "secrecy_level": i.secrecy_level,
                        "alter_cause": i.alter_cause,
                        "alter_front": i.alter_front,
                        "alter_later": i.alter_later,
                        "file": None,
                        "enabled": bool(i.enabled),
                        "valid": bool(i.valid)
                    }

                file_lsit = TbDepense.objects.filter(project_id=project_id_222).values_list("drawing_file_id", flat=1)
                all_file = TbDrawingFile.objects.filter(id__in=file_lsit)
                if TbDrawingFile.objects.filter(project_id=project_id_222):
                    type_list = \
                        TbDrawingFile.objects.filter(project_id=project_id_222).values_list(
                            "drawing_type__drawing_type",
                            "dev_type")[0]
                else:
                    type_list = [None, None]
                # print(all_file)
                if all_file:
                    for k in all_file.values():
                        file_path = k['seal_filepath']

                        files.append({'id': k['id'], 'file_name': k['file_name'], 'file_size': k['file_size'],
                                      'file_path': file_path, 'uploader': k['uploader'],
                                      'create_time': k['create_time'].strftime("%Y-%m-%d %H:%M:%S"),
                                      'project_id': k['project_id'], 'file_type': k['file_type'],
                                      "dev_type": type_list[0],
                                      'drawing_type': type_list[1]})

                    content['payload']['file'] = files
                    return Response(content)

                    # 圖紙接受大類
            from files.models import TbCustomerPaper, TbProjectPaper
            if paper_type == "customer":  # 客戶

                customer_id = TbDepense.objects.filter(accptor=request.user, status=status).filter(
                    Q(product_type__contains=search) | Q(customer__case_name__contains=search)).values_list(
                    "customer_id",
                    flat=True).distinct()
                # print(customer_id)
                result_cu = TbCustomerPaper.objects.filter(id__in=customer_id, enabled=1).all()

                if result_cu:
                    for i in result_cu:
                        dispor = TbDepense.objects.filter(customer_id=i.id).values_list("distributor", flat=1)[0]
                        content["payload"]["data"].append({
                            "id": i.id,
                            "ecn_no": i.ecn_no,
                            "cutter_spec": i.custters_spec,
                            "case_name": i.case_name,
                            "priority": i.priority,
                            "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "version": i.version,
                            "cutter_type": i.p_name,
                            "distributor": dispor,
                            "type": "customer"
                        })
            elif paper_type == "project":
                project_id = TbDepense.objects.filter(accptor=request.user, status=status).filter(
                    Q(product_type__icontains=search) | Q(product_stage__icontains=search) | Q(
                        project__case_name__icontains=search)).values_list("project_id",
                                                                           flat=True).distinct()
                # print(project_id)
                result_pro = TbProjectPaper.objects.filter(id__in=project_id, enabled=1).all()
                if result_pro:
                    for i in result_pro:
                        dispor = TbDepense.objects.filter(project_id=i.id).values_list("distributor", flat=1)[0]
                        content["payload"]["data"].append({
                            "id": i.id,
                            "ecn_no": i.ecn_no,
                            "cutter_spec": i.custters_spec,
                            "case_name": i.case_no,
                            "priority": i.priority,
                            "create_time": i.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                            "version": i.version,
                            "distributor": dispor,
                            "stage_type": i.stage_type,
                            "cutter_type": i.cutter_type,
                            "type": "project"
                        })
            result = content["payload"]["data"]
            result = sorted(result, key=lambda result: result["create_time"], reverse=1)
            if page_num:
                pag_class = Paginator(result, 20)
            else:
                pag_class = Paginator(result, len(result) + 1)
                page_num = 1
            content["payload"]["page"] = {'count': pag_class.count, 'page': int(page_num),
                                          'page_number': pag_class.page_range[-1]}
            content["payload"]["data"] = (list(pag_class.page(page_num)))


        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    if request.method == "POST":
        from files.models import TbProjectPaper, TbCustomerPaper
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            customer_id = request.GET.get("customer_id", None)
            project_id = request.GET.get("project_id", None)
            if customer_id:
                status = TbDepense.objects.filter(accptor=request.user, customer_id=customer_id).values_list("status",
                                                                                                             flat=1)
                if status[0]:
                    content["errmsg"] = "文件已經取消！"
                    content["status"] = 0
                    return Response(content)
                TbDepense.objects.filter(accptor=request.user, customer_id=customer_id).update(status=1)
                all_status = TbDepense.objects.filter(customer_id=customer_id).values_list("status", flat=1)
                if 0 not in all_status:
                    TbCustomerPaper.objects.filter(id=customer_id).update(c_confirm=3)
            if project_id:
                status = TbDepense.objects.filter(accptor=request.user, project_id=project_id).values_list(
                    "status", flat=1)
                if status[0]:
                    content["errmsg"] = "文件已經取消！"
                    content["status"] = 0
                    return Response(content)
                TbDepense.objects.filter(accptor=request.user, project_id=project_id).update(status=1)
                all_status = TbDepense.objects.filter(project_id=project_id).values_list("status", flat=1)

                if 0 not in all_status:
                    TbProjectPaper.objects.filter(id=project_id).update(p_confirm=3)
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0

    return Response(content)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def customer_input(request):
    if request.method == "POST":
        content = {"payload": [], "status": 1, "errmsg": None}
        try:
            img_name = request.FILES.getlist('filename')
            image = str(img_name[0]).split('.')
            uid = str(uuid.uuid1())
            name = uid + '.' + image[-1]
            path = os.path.join(settings.MEDIA_ROOT, settings.DRAWING_PATH, name)
            # keep_path = os.path.join(settings.DRAWING_PATH, name)
            with open(path, 'wb') as flhd:
                flhd.write(img_name[0].read())
                flhd.close()
            data = xlrd.open_workbook(path, 'rb')
            table = data.sheet_by_index(0)
            excel_list = []
            from customer.models import TbCustomInfo
            for r in range(1, table.nrows):
                a = table.cell(r, 0).value
                b = table.cell(r, 1).value
                c = table.cell(r, 2).value
                d = table.cell(r, 3).value
                e = table.cell(r, 4).value
                excel_list.append(TbCustomInfo(c_name=a, c_name_short=b, c_num=c, c_type=d, c_site=e, delete_flag=1))
            TbCustomInfo.objects.bulk_create(excel_list)
            os.remove(path)
        except Exception as e:
            content["errmsg"] = str(e)
            content["status"] = 0
        return Response(content)
@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
def update(request):
    if request.method == "GET":
        content = {"payload": "Success", "status": 1, "errmsg": None}
        printing_data()
        despense_data()
        return Response(content)
